package com.administrator.scoreManageSys.service.impl;

import com.administrator.scoreManageSys.entity.system.User;
import com.administrator.scoreManageSys.mapper.organization.OrganizationMapper;
import com.administrator.scoreManageSys.service.OrganizationService;
import com.administrator.scoreManageSys.utils.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import static com.administrator.scoreManageSys.system.SystemConstant.DEFAULT_PASSWORD;
import static com.administrator.scoreManageSys.system.SystemConstant.MD5_KEY;

/**
 * @author zsh
 * @date 2022/04/06/ 11:20
 */
@Service
public class OrganizationServiceImpl implements OrganizationService {
    @Resource
    private OrganizationMapper organizationMapper;
    @Resource
    private ResultUtils resultUtils;
    @Resource
    private Md5Utils md5Utils;

    /**
     * 获取用户账户列表
     *
     * @param pageNum  当前页
     * @param pageSize 页大小
     * @param roleId   角色id
     * @param phone    手机号
     * @param name     名称
     * @return 用户账户列表
     */
    @Override
    public JSONObject userAccountList(Integer pageNum, Integer pageSize, Long roleId, Long phone, String name) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> userList = organizationMapper.userAccountList(roleId, phone, name);
        PageInfo<User> pageInfo = new PageInfo<>(userList);
        return resultUtils.resultSuccessData(pageInfo);
    }

    /**
     * 添加用户账号
     *
     * @param userId              创建人
     * @param name                用户名称
     * @param phone               用户手机号
     * @param identity            用户身份  0:管理员 / 1:学生 /2:老师
     * @param roleId              用户角色id
     * @param sex                 性别 1/2 男/女
     * @param classId             用户班级id
     * @param identityCard        用户身份证号
     * @param idEntityCardAddress 用户身份证地址
     * @param address             现居住地址
     * @param admissionTime       入学时间
     * @return 操作结果
     */
    @Override
    public JSONObject userAccountAdd(Long userId, String name, Long phone, Long identity, Long roleId, Long sex, Long classId, String identityCard, String idEntityCardAddress, String address, Long admissionTime) {
        long createTime = System.currentTimeMillis();
        if (identity == 1) {
            User user = defaultGenerate(admissionTime);
            user.setCreateUser(userId);
            user.setUserName(name);
            user.setPhone(phone);
            user.setIdentity(identity);
            user.setRole(roleId);
            user.setSex(sex);
            user.setClassId(classId);
            user.setIdentityCard(identityCard);
            user.setIdEntityCardAddress(idEntityCardAddress);
            user.setAddress(address);
            user.setCreateTime(createTime);
            //添加用户进入user
            organizationMapper.userAccountAdd(user);
            //关联对应班级
            organizationMapper.insertClassByUser(user.getId(), classId, 1);
        } else if (identity == 0) {
            User user = defaultGenerate(admissionTime);
            user.setCreateUser(userId);
            user.setUserName(name);
            user.setPhone(phone);
            user.setIdentity(identity);
            user.setCreateTime(createTime);
            user.setRole(roleId);
            user.setSex(sex);
            user.setClassId(classId);
            user.setIdentityCard(identityCard);
            user.setIdEntityCardAddress(idEntityCardAddress);
            user.setAddress(address);
            //添加用户进入user
            organizationMapper.userAccountAdd(user);
        } else {
            User user = defaultGenerate(admissionTime);
            user.setCreateUser(userId);
            user.setCreateTime(createTime);
            user.setUserName(name);
            user.setPhone(phone);
            user.setIdentity(identity);
            user.setRole(roleId);
            user.setSex(sex);
            user.setClassId(classId);
            user.setIdentityCard(identityCard);
            user.setIdEntityCardAddress(idEntityCardAddress);
            user.setAddress(address);
            //添加用户进入user
            organizationMapper.userAccountAdd(user);
            if (user.getClassId()!=null){
                //关联对应班级
                organizationMapper.insertClassByUser(user.getId(), classId, 2);
            }
        }
        return resultUtils.resultSuccess();
    }

    /**
     * 重置密保
     *
     * @param id 用户id
     * @return 操作结果
     */
    @Override
    public JSONObject resetPasswordProtection(Long id) {
        //删除用户所有密保
        organizationMapper.resetPasswordProtection(id);
        String password = md5Utils.encrypt(DEFAULT_PASSWORD + MD5_KEY);
        //修改用户密码
        organizationMapper.changePassword(id, password);
        return resultUtils.resultSuccessData(DEFAULT_PASSWORD);
    }

    /**
     * 重置密码
     *
     * @param id 用户id
     * @return 操作结果
     */
    @Override
    public JSONObject resetPassword(Long id) {
        String password = md5Utils.encrypt(DEFAULT_PASSWORD + MD5_KEY);
        //修改用户密码
        organizationMapper.changePassword(id, password);
        return resultUtils.resultSuccess();
    }

    /**
     * 修改用户账号
     * @param name 用户姓名
     * @param phone 用户手机号
     * @param roleId 用户角色id
     * @param classId 用户班级id
     * @param address 现居住地址
     * @param id 用户id
     * @param oldClassId 原班级id
     * @param identity 用户身份  0:管理员 / 1:学生 /2:老师
     * @param sex 性别 1/2 男/女
     * @param identityCard 用户身份证号
     * @param idEntityCardAddress 用户身份证地址
     * @param admissionTime 入学时间
     * @return 操作结果
     */
    @Override
    public JSONObject userAccountUpdate(String name, Long phone, Long roleId, Long classId, String address, Long id, Long oldClassId, Long identity, Long sex, String identityCard, String idEntityCardAddress, Long admissionTime) {
        User user = new User(id, name, phone, roleId, classId, address);
        user.setIdentity(identity);
        user.setSex(sex);
        user.setIdentityCard(identityCard);
        user.setIdEntityCardAddress(idEntityCardAddress);
        user.setAdmissionTime(admissionTime);
        //修改用户信息
        organizationMapper.userAccountUpdate(user);
        //修改班级关联信息
        if (StringUtil.isNotEmpty(String.valueOf(classId))) {
            organizationMapper.updateClassAndUser(id, oldClassId, classId);
        }
        return resultUtils.resultSuccess();
    }

    /**
     * 导出用户信息
     *
     * @param name     名称
     * @param phone    手机号
     * @param roleId   角色id
     * @param response response
     */
    @Override
    public void exportUserList(String name, Long phone, Long roleId, HttpServletResponse response) {
        List<User> userList = organizationMapper.exportUserList(roleId, phone, name);
        //导出
        downloadExcel(response, userList);
    }

    /**
     * 删除账户
     *
     * @param id 账户id
     * @return 操作结果
     */
    @Override
    public JSONObject deleteAccount(Long id) {
        organizationMapper.deleteAccount(id);
        return resultUtils.resultSuccess();
    }

    /**
     * 获取用户详情信息
     *
     * @param id 用户id
     * @return 详情信息
     */
    @Override
    public JSONObject getUserDetail(Long id) {
      JSONObject user= organizationMapper.getUserDetail(id);
        return resultUtils.resultSuccessData(user);
    }

    /**
     * 生成默认数据
     *
     * @param admissionTime 入职/入学时间
     * @return 默认用户
     */
    public User defaultGenerate(Long admissionTime) {
        int checkAccount = 1;
        String account = "";
        String password = "";
        String userNumber = "";
        while (checkAccount > 0) {
            //生成账号 字母为首的八位数  密码 a123456
            account = NumberUtils.getRandomPassword(8);
            password = md5Utils.encrypt(DEFAULT_PASSWORD + MD5_KEY);
            //生成学号 入学年份 20211223 + 随机生成四位数 1234 = 202112231234
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String sd = sdf.format(new Date(Long.parseLong(String.valueOf(admissionTime))));
            userNumber = sd + NumberUtils.getRandomNumber(4);
            //检查生成账号学号是否存在重复
            checkAccount = organizationMapper.checkAccount(account, userNumber);
        }
        //检查userNumber是否为仅数字
        if (userNumber.chars().allMatch(Character::isLetter)) {
            return new User(account, password, Long.valueOf(userNumber), admissionTime);
        } else {
            return new User(account, password, Long.valueOf(userNumber.replaceAll("[^0-9]", "")), admissionTime);
        }

    }

    private void downloadExcel(HttpServletResponse response, List<User> list) {
        StringBuilder stringBuffer = new StringBuilder();
        stringBuffer.append("用户账号信息表");
        Map<String, String> titleMap = new LinkedHashMap<>();
        titleMap.put("id", "id");
        titleMap.put("userName", "真实姓名");
        titleMap.put("phone", "手机号");
        titleMap.put("roleName", "用户角色");
        titleMap.put("account", "账号");
        titleMap.put("userNumber", "学号/工号");
        titleMap.put("gender", "性别");
        titleMap.put("admissionTimeName", "入学时间/工作时间");
        titleMap.put("className", "班级");
        titleMap.put("identityCard", "身份证号");
        titleMap.put("idEntityCardAddress", "身份证地址");
        titleMap.put("address", "现居住地址");
        titleMap.put("creationTime", "创建时间");
        titleMap.put("userIdentity", "用户身份");
        ExportExcelList ex1 = new ExportExcelList();
        //设置表头宽度
        Integer[] headersL = {16, 30, 22, 22, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16};
        try {
            ExportExcelUtil x = new ExportExcelUtil();
            List<Map<String, Object>> listMap = JSONArray.parseObject(JSON.toJSONString(list), new TypeReference<List<Map<String, Object>>>() {
            });
            x.isLand = true;
            x.exportExcel(ex1, listMap, stringBuffer.toString(), titleMap, headersL, stringBuffer.toString(), 1, response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
